/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.shelf.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.bookset.entity.BkPlace;
import com.thinkgem.jeesite.modules.bookset.service.BookPlaceService;
import com.thinkgem.jeesite.modules.shelf.entity.BkShelf;
import com.thinkgem.jeesite.modules.shelf.service.BkShelfService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 书架管理Controller
 * @author ZC
 * @version 2017-05-15
 */
@Controller
@RequestMapping(value = "${adminPath}/shelf/bkShelf")
public class BkShelfController extends BaseController {

	@Autowired
	private BkShelfService bkShelfService;
    @Autowired
    private BookPlaceService bookPlaceService;
	
	@ModelAttribute
	public BkShelf get(@RequestParam(required=false) String id) {
		BkShelf entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = bkShelfService.get(id);
		}
		if (entity == null){
			entity = new BkShelf();
		}
		return entity;
	}
	
	@RequiresPermissions("shelf:bkShelf:view")
	@RequestMapping(value = {"list", ""})
	public String list(BkShelf bkShelf, Model model) {
        List<BkShelf> shelflist = bkShelfService.findList(bkShelf);

        List<BkShelf> list = new LinkedList<>();

        BkPlace bkPlace = new BkPlace();
        bkPlace.setGcdName(bkShelf.getName());
        Page<BkPlace> place = bookPlaceService.getAll(new Page<BkPlace>(), bkPlace);
        List<BkPlace> places = place.getList();
        if(null != places && !places.isEmpty()){
            BkShelf temBkShelf;
            for(BkPlace temBkPlace:places){
                temBkShelf = new BkShelf();
                String shelfId = temBkPlace.getId();
                temBkShelf.setId(shelfId);
                temBkShelf.setName(temBkPlace.getGcdName());
                temBkShelf.setRemarks("书库");
                list.add(temBkShelf);
                for(int i = shelflist.size() - 1; i >= 0; i--){
                    BkShelf item = shelflist.get(i);
                    if(shelfId.equals(item.getParentId())){
                        list.add(item);
                        shelflist.remove(i);
                    }
                }

            }
        }

        while(true){
            // 是否还有子节点
            boolean flag;
            if(!CollectionUtils.isEmpty(shelflist)){
                flag = false;
                for(int i = shelflist.size() - 1; i >= 0; i--){
                    BkShelf item = shelflist.get(i);
                    for(int k = 0; k < list.size(); k++){
                        BkShelf itemPar = list.get(k);
                        if(itemPar.getId().equals(item.getParentId())){
                            flag = true;
                            list.add(i + 2, item);
                            shelflist.remove(item);
                            if(CollectionUtils.isEmpty(shelflist)){
                                break;
                            }
                        }
                    }
                }
            }
            else{
                break;
            }
            if(!flag){
                break;
            }
        }

		model.addAttribute("list", list);
		return "modules/shelf/bkShelfList";
	}

	@RequiresPermissions("shelf:bkShelf:view")
	@RequestMapping(value = "form")
	public String form(BkShelf bkShelf, Model model) {
        if("0".equals(bkShelf.getParentId())){
            return "redirect:" + Global.getAdminPath() + "/bookset/place/form?id=" + bkShelf.getId();
        }
        else{
            if(bkShelf.getParent() != null && StringUtils.isNotBlank(bkShelf.getParent().getId())){
                bkShelf.setParent(bkShelfService.get(bkShelf.getParent().getId()));
                // 获取排序号，最末节点排序号+30
                if(StringUtils.isBlank(bkShelf.getId())){
                    BkShelf bkShelfChild = new BkShelf();
                    bkShelfChild.setParent(new BkShelf(bkShelf.getParent().getId()));
                    List<BkShelf> list = bkShelfService.findList(bkShelf);
                    if(list.size() > 0){
                        bkShelf.setSort(list.get(list.size() - 1).getSort());
                        if(bkShelf.getSort() != null){
                            bkShelf.setSort(bkShelf.getSort() + 30);
                        }
                    }
                }
            }
            if(bkShelf.getSort() == null){
                bkShelf.setSort(30);
            }
            model.addAttribute("bkShelf", bkShelf);
            return "modules/shelf/bkShelfForm";
        }
    }

	@RequiresPermissions("shelf:bkShelf:edit")
	@RequestMapping(value = "save")
	public String save(BkShelf bkShelf, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, bkShelf)){
			return form(bkShelf, model);
		}
		bkShelfService.save(bkShelf);
		addMessage(redirectAttributes, "保存书架成功");
		return "redirect:"+Global.getAdminPath()+"/shelf/bkShelf/?repage";
	}
	
	@RequiresPermissions("shelf:bkShelf:edit")
	@RequestMapping(value = "delete")
	public String delete(BkShelf bkShelf, RedirectAttributes redirectAttributes) {
		bkShelfService.delete(bkShelf);
		addMessage(redirectAttributes, "删除书架成功");
		return "redirect:"+Global.getAdminPath()+"/shelf/bkShelf/?repage";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		// 设置 一级节点为图书馆
        Page<BkPlace> place = bookPlaceService.getAll(new Page<BkPlace>(), new BkPlace());
        List<BkPlace> places = place.getList();
        if(null != places && !places.isEmpty()){
            for(BkPlace bkPlace:places){
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", bkPlace.getId());
                map.put("pId", 0);
                map.put("name", bkPlace.getGcdName());
                mapList.add(map);
            }
        }

        List<BkShelf> list = bkShelfService.findList(new BkShelf());
		for(BkShelf e : list){
			if(StringUtils.isBlank(extId) || !extId.equals(e.getId()) && !e.getParentIds().contains("," + extId + ",")){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
}